package com.guoguo.cloudmusic.ui.login

import android.content.Intent
import android.graphics.Color
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.guoguo.cloudmusic.R
import com.guoguo.cloudmusic.databinding.ActivityLoginBinding
import com.guoguo.cloudmusic.extension.md5Encode
import com.guoguo.cloudmusic.ui.MainActivity
import com.guoguo.cloudmusic.ui.common.BaseActivity
import com.guoguo.cloudmusic.utils.XToastUtils
import com.xuexiang.xui.utils.WidgetUtils
import com.xuexiang.xui.widget.dialog.LoadingDialog

/**
 * 登录界面
 * @author GuoGuo
 * @date 2021/12/15
 */
class LoginActivity : BaseActivity() {
    private val viewModel by lazy {
        ViewModelProvider(this).get(LoginViewModel::class.java)
    }
    private var _binding: ActivityLoginBinding? = null
    private val binding: ActivityLoginBinding
        get() = _binding!!
    private lateinit var mLoadingDialog: LoadingDialog

    override fun initBinding() {
        super.initBinding()
        mLoadingDialog = WidgetUtils.getLoadingDialog(this)
            .setIconScale(0.4f)
            .setLoadingSpeed(8)
        _binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }

    override fun initListener() {
        super.initListener()
        val username = binding.etPhoneNumber as TextView
        val pwd = binding.etVerifyCode as TextView
        val protocol = binding.cbProtocol
        binding.btnLogin.setOnClickListener {
            if (username.text.isEmpty() || pwd.text.isEmpty()) {
                return@setOnClickListener XToastUtils.error("用户名或密码不能为空")
            } else if (!protocol.isChecked) {
                return@setOnClickListener XToastUtils.warning("请同意用户协议与隐私政策");
            } else {
                mLoadingDialog.show()
                val data = LoginUser(
                    userName = username.text.toString(),
                    md5_password = pwd.text.toString().md5Encode()
                )
                viewModel.login(data)
            }
        }
    }

    override fun initObserver() {
        super.initObserver()
        viewModel.userInfoLiveData.observe(this, Observer {
            val account = it.getOrNull()
            mLoadingDialog.dismiss()
            if (account != null) {
                val intent = Intent(this, MainActivity::class.java)
                startActivity(intent)
                finish()
            }
        })
    }

    override fun initBar() {
        super.initBar()
        window.statusBarColor = Color.WHITE
    }
}